#include "virtualthumbnailview.h"
#include "minimalmemorymanager.h"
#include "nextgen_placeholder.h"
#include <QScrollBar>
#include <QApplication>
#include <QPainter>
#include <QMouseEvent>
#include <QWheelEvent>
#include <QDebug>
#include <QThread>
#include <QDir>
#include <QFileInfo>
#include <QDateTime>
#include <QFile>
#include <QListWidgetItem>
#include <QPixmap>
#include <QIcon>
#include <QMetaObject>
#include <QMutex>
#include <QMutexLocker>
#include <algorithm> // for std::sort
VirtualThumbnailView::VirtualThumbnailView(QWidget *parent)
    : QListWidget(parent)
    , m_currentFileIdentity("")
    , m_totalPages(0)
    , m_scrollPosition(0)
    , m_viewportHeight(0)
    , m_itemHeight(220)  // 恢复默认高度
    , m_itemWidth(190)   // 恢复默认宽度
    , m_spacing(2)  // 减少缩略图间距
    , m_scrollTimer(nullptr)
    , m_loadTimer(nullptr)
    , m_memoryTimer(nullptr)
    , m_progressiveTimer(nullptr)
    , m_bufferSize(50)           // 进一步放大缓冲区到50个项目，提高滚动体验
    , m_maxLoadedItems(300)      // 放大最大加载数到300个项目，减少内存清理频率
    , m_isScrolling(false)
    , m_progressiveLoadingEnabled(true)
    , m_progressiveUpdateInterval(2000)
    , m_cacheManager(UnifiedCacheManager::instance())
    , m_unifiedMemoryManager(nullptr)  // TDD: 初始化统一内存管理器指针
    , m_lastSelectedIndex(-1)  // 初始化重复点击防护
{
    initializeView();
    setupTimers();
    setupScrollBar();
}
VirtualThumbnailView::~VirtualThumbnailView()
{
    if (m_scrollTimer) {
        m_scrollTimer->stop();
        delete m_scrollTimer;
    }
    if (m_loadTimer) {
        m_loadTimer->stop();
        delete m_loadTimer;
    }
    if (m_memoryTimer) {
        m_memoryTimer->stop();
        delete m_memoryTimer;
    }
    if (m_progressiveTimer) {
        m_progressiveTimer->stop();
        delete m_progressiveTimer;
    }
}
void VirtualThumbnailView::initializeView()
{
    // 设置基本属性 - 保持图标尺寸不变，让容器全宽
    setViewMode(QListWidget::IconMode);
    setIconSize(QSize(m_itemWidth, m_itemHeight)); // 图标保持原尺寸
    setSpacing(m_spacing);
    setMovement(QListWidget::Static);
    setResizeMode(QListWidget::Adjust);
    // 设置文字在图标下方，并控制间距
    setWordWrap(true);
    setTextElideMode(Qt::ElideNone);
    // 设置居中对齐
    setItemAlignment(Qt::AlignCenter);
    setGridSize(QSize(m_itemWidth + 20, m_itemHeight + 40)); // 恢复基于项目尺寸的网格
    setUniformItemSizes(true); // 确保所有项目大小一致
    // 隐藏水平滚动条
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    // 设置垂直滚动条
    setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    // 连接信号
    connect(this, &QListWidget::currentRowChanged, this, [this](int row) {
        // 只有当选中的索引发生变化时才发射信号，防止重复点击同一索引导致页面重复刷新
        if (row != m_lastSelectedIndex) {
            m_lastSelectedIndex = row;
            emit thumbnailSelected(row);
        } else {
        }
    });
    // 设置最小尺寸
    setMinimumSize(140, 200);
    // 设置专业的高亮样式，调整边框位置避免覆盖页码
    setStyleSheet(R"(
        QListWidget::item {
            border: 2px solid transparent;
            border-radius: 5px;
            padding: 2px 5px 8px 5px;  /* 上2px，左右5px，下8px为页码预留空间 */
            margin: 1px;               /* 减少间距 */
            background-color: transparent;
            color: black;
            text-align: center;
            icon-alignment: center;
        }
        QListWidget::item:selected {
            border: 3px solid rgb(0, 122, 255);
            background-color: rgba(0, 122, 255, 40);
            color: black;
            font-weight: bold;
            padding: 1px 4px 8px 4px;  /* 选中时调整padding配合border */
            text-align: center;
        }
        QListWidget::item:hover {
            border: 2px solid rgba(0, 122, 255, 120);
            background-color: rgba(0, 122, 255, 20);
            color: black;
            padding: 2px 5px 8px 5px;
            text-align: center;
        }
        QListWidget::item:selected:hover {
            border: 3px solid rgb(0, 122, 255);
            background-color: rgba(0, 122, 255, 60);
            color: black;
            font-weight: bold;
            padding: 1px 4px 8px 4px;
            text-align: center;
        }
        QListWidget {
            font-size: 12px;
        }
    )");
}
void VirtualThumbnailView::setupTimers()
{
    // 滚动定时器 - 用于检测滚动结束
    m_scrollTimer = new QTimer(this);
    m_scrollTimer->setSingleShot(true);
    m_scrollTimer->setInterval(100); // 100ms后认为滚动结束
    connect(m_scrollTimer, &QTimer::timeout, this, &VirtualThumbnailView::onScrollTimer);
    // 加载定时器 - 用于批量加载缩略图
    m_loadTimer = new QTimer(this);
    m_loadTimer->setSingleShot(true);
    m_loadTimer->setInterval(50); // 50ms后开始加载
    connect(m_loadTimer, &QTimer::timeout, this, &VirtualThumbnailView::onLoadTimer);
    // 内存清理定时器 - 用于定期清理内存
    m_memoryTimer = new QTimer(this);
    m_memoryTimer->setInterval(5000); // 每5秒清理一次，减少频率
    connect(m_memoryTimer, &QTimer::timeout, this, &VirtualThumbnailView::onMemoryCleanupTimer);
    m_memoryTimer->start();
    // 渐进式更新定时器 - 用于检查新生成的缩略图
    m_progressiveTimer = new QTimer(this);
    m_progressiveTimer->setInterval(m_progressiveUpdateInterval);
    connect(m_progressiveTimer, &QTimer::timeout, this, &VirtualThumbnailView::onProgressiveUpdateTimer);
    // 默认不启动，只在文件处理时启动
}
void VirtualThumbnailView::setupScrollBar()
{
    // 设置滚动条样式
    verticalScrollBar()->setStyleSheet(
        "QScrollBar:vertical {"
        "    background: #f0f0f0;"
        "    width: 12px;"
        "    border-radius: 6px;"
        "}"
        "QScrollBar::handle:vertical {"
        "    background: #c0c0c0;"
        "    border-radius: 6px;"
        "    min-height: 20px;"
        "}"
        "QScrollBar::handle:vertical:hover {"
        "    background: #a0a0a0;"
        "}"
    );
}
void VirtualThumbnailView::setThumbnails(const QList<QImage>& thumbnails)
{
    // 清空现有数据
    m_allItems.clear();
    m_visibleItems.clear();
    m_lastSelectedIndex = -1;  // 重置选中索引
    clear(); // 清空QListWidget的所有项目
    // 创建所有项目
    for (int i = 0; i < thumbnails.size(); ++i) {
        ThumbnailItem item;
        item.index = i;
        item.thumbnail = thumbnails[i];
        item.isLoaded = !thumbnails[i].isNull();
        item.isLoading = false;
        item.position = QRect(0, i * (m_itemHeight + m_spacing), m_itemWidth, m_itemHeight);
        m_allItems.append(item);
        // 创建QListWidgetItem
        QListWidgetItem* listItem = new QListWidgetItem();
        listItem->setSizeHint(QSize(m_itemWidth, m_itemHeight + m_spacing));
        // 如果缩略图有效，直接设置图标
        if (!thumbnails[i].isNull()) {
            QPixmap pixmap = QPixmap::fromImage(thumbnails[i]);
            listItem->setIcon(QIcon(pixmap));
        } else {
            // 创建占位符
            QImage placeholder = NextGenPlaceholder::createLoading(QSize(m_itemWidth, m_itemHeight), "加载缩略图...");
            QPixmap pixmap = QPixmap::fromImage(placeholder);
            listItem->setIcon(QIcon(pixmap));
        }
        addItem(listItem);
    }
    // 更新滚动条
    updateScrollBar();
    // 开始加载可见缩略图
    m_loadTimer->start();
}
void VirtualThumbnailView::setThumbnailsFromCache(const QString& fileIdentity, int totalPages)
{
    // 如果文件标识相同且总页数相同，跳过重复设置
    if (m_currentFileIdentity == fileIdentity && m_totalPages == totalPages) {
        return;
    }
    m_currentFileIdentity = fileIdentity;
    m_totalPages = totalPages;
    // 清空现有数据
    m_allItems.clear();
    m_visibleItems.clear();
    m_lastSelectedIndex = -1;  // 重置选中索引
    clear(); // 清空QListWidget的所有项目
    // 创建所有项目（初始为占位符）
    for (int i = 0; i < totalPages; ++i) {
        ThumbnailItem item;
        item.index = i;
        item.isLoaded = false;
        item.isLoading = false;
        item.position = QRect(0, i * (m_itemHeight + m_spacing), m_itemWidth, m_itemHeight);
        item.cachePath = getThumbnailCachePath(i);
        // 先添加到列表，再创建占位符
        m_allItems.append(item);
        // 创建QListWidgetItem并添加到QListWidget
        QListWidgetItem* listItem = new QListWidgetItem(this);
        listItem->setSizeHint(QSize(m_itemWidth, m_itemHeight + 28)); // 为页码文字预留空间
        listItem->setText(QString("%1").arg(i + 1)); // 显示页码，更清晰
        listItem->setTextAlignment(Qt::AlignCenter);
        // 设置初始占位符图标
        QImage placeholder = NextGenPlaceholder::createLoading(QSize(m_itemWidth, m_itemHeight), "加载缩略图...");
        QPixmap pixmap = QPixmap::fromImage(placeholder);
        listItem->setIcon(QIcon(pixmap));
    }
    // 更新滚动条
    updateScrollBar();
    // 强制刷新显示
    update();
    repaint();
    // 开始加载可见缩略图
    m_loadTimer->start();
    // **关键修复**: 强制启动渐进式加载，确保能检测到新生成的缓存文件
    enableProgressiveLoading(true);
    // **修复**: 立即尝试加载可见区域的缩略图
    QTimer::singleShot(100, this, [this]() {
        loadVisibleThumbnails();
    });
}
int VirtualThumbnailView::getCurrentThumbnailIndex() const
{
    return currentRow();
}
void VirtualThumbnailView::scrollToThumbnail(int index)
{
    if (index < 0 || index >= m_allItems.size()) {
        return;
    }
    // 计算目标位置
    int targetY = index * (m_itemHeight + m_spacing);
    // 平滑滚动到目标位置
    verticalScrollBar()->setValue(targetY);
}
void VirtualThumbnailView::updateThumbnail(int index, const QImage& thumbnail)
{
    if (index < 0 || index >= m_allItems.size()) {
        return;
    }
    ThumbnailItem& item = m_allItems[index];
    item.thumbnail = thumbnail;
    item.isLoaded = !thumbnail.isNull();
    item.isLoading = false;
    // 更新对应的QListWidgetItem图标
    if (index < count() && !thumbnail.isNull()) {
        QListWidgetItem* listItem = this->item(index);
        if (listItem) {
            QPixmap pixmap = QPixmap::fromImage(thumbnail);
            listItem->setIcon(QIcon(pixmap));
        }
    }
    // 如果项目可见，立即更新显示
    if (isItemVisible(index)) {
        update();
    }
}
void VirtualThumbnailView::paintEvent(QPaintEvent *event)
{
    // 直接调用父类的paintEvent，让QListWidget处理所有绘制
    // 我们通过QListWidgetItem的图标来显示缩略图，不需要自定义绘制
    QListWidget::paintEvent(event);
}
void VirtualThumbnailView::resizeEvent(QResizeEvent *event)
{
    QListWidget::resizeEvent(event);
    m_viewportHeight = height();
    // 重新计算项目位置
    calculateItemPositions();
    // 更新滚动条
    updateScrollBar();
    // 开始加载可见缩略图
    m_loadTimer->start();
}
void VirtualThumbnailView::scrollContentsBy(int dx, int dy)
{
    QListWidget::scrollContentsBy(dx, dy);
    // 更新滚动位置
    m_scrollPosition = verticalScrollBar()->value();
    // 重置滚动定时器
    if (m_scrollTimer) {
        m_scrollTimer->start();
    }
    // **积极策略**: 滚动时立即尝试加载，同时使用定时器作为备用
    if (m_loadTimer && !m_loadTimer->isActive()) {
        m_loadTimer->start();
    }
    // **立即加载**: 滚动时立即尝试加载可见区域的缩略图
    QTimer::singleShot(10, this, [this]() {
        loadVisibleThumbnails();
    });
    // **新增**：检查是否需要请求更多缩略图（动态边界扩展）
    requestMoreThumbnailsIfNeeded();
}
void VirtualThumbnailView::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        // 使用系统默认的定位机制，而不是自定义计算
        QListWidgetItem* item = itemAt(event->pos());
        if (item) {
            int index = row(item);
            if (index >= 0 && index < m_allItems.size()) {
                // 只有当点击的索引与上次不同时才发射信号，防止重复点击同一索引导致页面重复刷新
                if (index != m_lastSelectedIndex) {
                    emit thumbnailClicked(index);
                    setCurrentRow(index);
                } else {
                }
            }
        }
    }
    QListWidget::mousePressEvent(event);
}
void VirtualThumbnailView::wheelEvent(QWheelEvent *event)
{
    QListWidget::wheelEvent(event);
    // 重置滚动定时器
    m_scrollTimer->start();
    // 开始加载可见缩略图
    m_loadTimer->start();
}
void VirtualThumbnailView::onScrollTimer()
{
    // 滚动停止后，触发缩略图加载
    if (m_loadTimer && !m_loadTimer->isActive()) {
        m_loadTimer->start();
    }
}
void VirtualThumbnailView::onLoadTimer()
{
    loadVisibleThumbnails();
}
void VirtualThumbnailView::onMemoryCleanupTimer()
{
    manageThumbnailMemory();
}
void VirtualThumbnailView::onProgressiveUpdateTimer()
{
    if (m_progressiveLoadingEnabled && !m_currentFileIdentity.isEmpty()) {
        performProgressiveUpdate();
    }
}
void VirtualThumbnailView::updateVisibleItems()
{
    // 计算可见区域
    int startY = m_scrollPosition;
    int endY = startY + m_viewportHeight;
    // 清空可见项目列表
    m_visibleItems.clear();
    // 添加可见项目
    for (int i = 0; i < m_allItems.size(); ++i) {
        const ThumbnailItem& item = m_allItems[i];
        if (item.position.bottom() >= startY && item.position.top() <= endY) {
            m_visibleItems.append(&m_allItems[i]);
        }
    }
}
void VirtualThumbnailView::calculateItemPositions()
{
    for (int i = 0; i < m_allItems.size(); ++i) {
        ThumbnailItem& item = m_allItems[i];
        item.position = QRect(0, i * (m_itemHeight + m_spacing), m_itemWidth, m_itemHeight);
    }
}
void VirtualThumbnailView::renderVisibleItems()
{
    update();
}
// 检查UI是否需要更新（检测占位符图标）
bool VirtualThumbnailView::needsUIUpdate(QListWidgetItem* listItem, const ThumbnailItem& item, int index) const
{
    if (!listItem) return false;
    // 检查图标是否为空
    if (listItem->icon().isNull()) {
        return true;
    }
    // 检查图标是否是占位符（通过检查图标尺寸差异）
    QPixmap currentPixmap = listItem->icon().pixmap(QSize(100, 100));
    if (currentPixmap.isNull()) {
        return true;
    }
    QSize currentSize = currentPixmap.size();
    QSize expectedSize = item.thumbnail.size();
    // 占位符通常尺寸较小且固定，真实缩略图尺寸较大
    if (currentSize.width() < expectedSize.width() * 0.8 || 
        currentSize.height() < expectedSize.height() * 0.8) {
        return true;
    }
    return false;
}
void VirtualThumbnailView::loadVisibleThumbnails()
{
    // 降低调试输出
    if (m_allItems.isEmpty()) {
        // 降低调试输出
        return;
    }
    // **修复**: 正确使用Qt的可见项目检测
    QRect visibleRect = viewport()->rect();
    // 获取可见范围的项目索引
    int startIndex = -1;
    int endIndex = -1;
    // **彻底修复**: 直接遍历当前屏幕上真正可见的项目
    QRect viewportRect = viewport()->rect();
    // 降低调试输出
    // 直接检查所有项目的可见性（但优化为只检查可能可见的范围）
    for (int i = 0; i < count(); ++i) {
        QListWidgetItem* item = this->item(i);
        if (!item) continue;
        QRect itemRect = visualItemRect(item);
        bool isVisible = itemRect.intersects(viewportRect);
        // 如果项目可见
        if (isVisible) {
            if (startIndex == -1) {
                startIndex = i;  // 第一个可见项目
            }
            endIndex = i;  // 最后一个可见项目
        }
        // 优化：如果已经找到可见项目，并且当前项目不可见且在可见区域下方，停止搜索
        if (startIndex != -1 && !isVisible && itemRect.top() > viewportRect.bottom()) {
            break;
        }
    }
    // **关键修复**: 如果没有找到可见项目，使用数学计算作为备选
    if (startIndex == -1 || endIndex == -1) {
        int scrollValue = verticalScrollBar()->value();
        int viewportHeight = viewport()->height();
        int itemTotalHeight = m_itemHeight + m_spacing;
        int mathStartIndex = qMax(0, scrollValue / itemTotalHeight);
        int mathEndIndex = qMin(count() - 1, (scrollValue + viewportHeight) / itemTotalHeight);
        if (startIndex == -1) startIndex = mathStartIndex;
        if (endIndex == -1) endIndex = mathEndIndex;
    }
    // 确保索引安全
    startIndex = qBound(0, startIndex, count() - 1);
    endIndex = qBound(startIndex, endIndex, count() - 1);
    // 添加缓冲区
    int bufferSize = m_bufferSize;
    int originalStart = startIndex;
    int originalEnd = endIndex;
    startIndex = qMax(0, startIndex - bufferSize);
    endIndex = qMin(m_allItems.size() - 1, endIndex + bufferSize);
        // 只加载可见区域内的缩略图
        for (int i = startIndex; i <= endIndex; ++i) {
            if (i < 0 || i >= m_allItems.size()) {
                continue;
            }
            ThumbnailItem& item = m_allItems[i];
            // 如果正在加载，跳过
            if (item.isLoading) {
                continue;
            }
        // **关键修复**: 只有在已经有真实缩略图时才跳过
        if (item.isLoaded && !item.thumbnail.isNull()) {
            // 跳过已加载的缩略图
            // **关键修复**: 即使跳过加载，也要检查UI是否需要更新
            if (i < count()) {
                QListWidgetItem* listItem = this->item(i);
                if (listItem) {
                    // 检查UI是否需要更新（检测占位符图标）
                    bool needsUpdate = needsUIUpdate(listItem, item, i);
                    if (needsUpdate) {
                        QPixmap pixmap = QPixmap::fromImage(item.thumbnail);
                        listItem->setIcon(QIcon(pixmap));
                        update(indexFromItem(listItem));
                    } else {
                    }
                }
            }
            continue; // 已经有真实缩略图，跳过
        }
        // TDD: 只使用统一缓存加载，不回退！
        QImage unifiedThumbnail = loadThumbnailFromUnifiedCache(i);
        if (!unifiedThumbnail.isNull()) {
            // 统一加载成功，更新项目
            item.thumbnail = unifiedThumbnail.scaled(m_itemWidth, m_itemHeight, 
                                                   Qt::KeepAspectRatio, Qt::SmoothTransformation);
            item.isLoaded = true;
            item.isLoading = false;
            // 更新UI
            if (i < count()) {
                QListWidgetItem* listItem = this->item(i);
                if (listItem) {
                    QPixmap pixmap = QPixmap::fromImage(item.thumbnail);
                    listItem->setIcon(QIcon(pixmap));
                    update(indexFromItem(listItem));
                } else {
                }
            } else {
            }
        } else {
            // 统一加载失败，创建占位符（不再回退到旧方法）
            item.isLoading = false;
            createPlaceholder(i);
        }
        // 检查是否成功加载
        if (item.isLoaded && !item.thumbnail.isNull()) {
        } else {
            // 如果缓存中没有，创建占位符
            createPlaceholder(i);
        }
    }
    // 清理远离可见区域的项目
    manageThumbnailMemory();
    // 停止加载定时器，避免重复处理
    if (m_loadTimer && m_loadTimer->isActive()) {
        m_loadTimer->stop();
    }
}
void VirtualThumbnailView::loadThumbnailAsync(int index)
{
    if (index < 0 || index >= m_allItems.size()) {
        return;
    }
    ThumbnailItem& item = m_allItems[index];
    if (item.isLoaded || item.isLoading) {
        return;
    }
    item.isLoading = true;
    // 异步加载缩略图
    QThread::msleep(10); // 模拟异步加载
    if (m_currentFileIdentity.isEmpty()) {
        // 没有文件标识，创建占位符
        createPlaceholder(index);
    } else {
        // TDD: 使用统一缓存加载替代旧方法
        QImage unifiedThumbnail = loadThumbnailFromUnifiedCache(index);
        if (!unifiedThumbnail.isNull()) {
            // 处理加载成功的逻辑（简化版）
            ThumbnailItem& item = m_allItems[index];
            item.thumbnail = unifiedThumbnail.scaled(m_itemWidth, m_itemHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation);
            item.isLoaded = true;
            item.isLoading = false;
            // 更新UI
            if (index < count()) {
                QListWidgetItem* listItem = this->item(index);
                if (listItem) {
                    QPixmap pixmap = QPixmap::fromImage(item.thumbnail);
                    listItem->setIcon(QIcon(pixmap));
                }
            }
        } else {
            // 加载失败，创建占位符
            createPlaceholder(index);
        }
    }
}
// TDD: 旧的loadThumbnailFromCache方法已删除，现在只使用统一缓存管理
void VirtualThumbnailView::createPlaceholder(int index)
{
    if (index < 0 || index >= m_allItems.size()) {
        return;
    }
    ThumbnailItem& item = m_allItems[index];
    // 使用统一的占位符创建方法
    QImage placeholder = NextGenPlaceholder::createLoading(QSize(m_itemWidth, m_itemHeight), "加载缩略图...");
    item.thumbnail = placeholder;
    item.isLoaded = false; // **关键修复**: 占位符不应标记为已加载，允许后续重新尝试
    item.isLoading = false;
    // 更新QListWidgetItem的显示
    QListWidgetItem* listItem = this->item(index);
    if (listItem) {
        QPixmap pixmap = QPixmap::fromImage(placeholder);
        listItem->setIcon(QIcon(pixmap));
        update(indexFromItem(listItem));
    }
}
void VirtualThumbnailView::manageThumbnailMemory()
{
    if (m_allItems.isEmpty()) {
        return;
    }
    // **彻底修复**: 使用数学计算，更可靠
    int scrollValue = verticalScrollBar()->value();
    int viewportHeight = viewport()->height();
    // 使用数学计算确定可见区域
    int startIndex = qMax(0, scrollValue / (m_itemHeight + m_spacing));
    int endIndex = qMin(count() - 1, (scrollValue + viewportHeight) / (m_itemHeight + m_spacing));
    // 确保索引有效
    startIndex = qBound(0, startIndex, count() - 1);
    endIndex = qBound(startIndex, endIndex, count() - 1);
    // 添加缓冲区，避免清理即将可见的项目
    int bufferSize = m_bufferSize * 3; // 使用3倍缓冲区，减少频繁的加载/释放
    startIndex = qMax(0, startIndex - bufferSize);
    endIndex = qMin(m_allItems.size() - 1, endIndex + bufferSize);
    int releasedCount = 0;
    int totalLoadedCount = 0;
    // 只清理远离可见区域的项目
    for (int i = 0; i < m_allItems.size(); ++i) {
        ThumbnailItem& item = m_allItems[i];
        if (item.isLoaded && !item.thumbnail.isNull()) {
            totalLoadedCount++;
        }
        // **优化内存策略**: 只有在内存使用超过阈值且远离可见区域时才清理
        if ((i < startIndex || i > endIndex) && item.isLoaded && !item.thumbnail.isNull()) {
            // 只有在总加载数超过最大限制时才开始清理
            if (totalLoadedCount <= m_maxLoadedItems) {
                continue; // 内存使用还在合理范围内，不清理
            }
            // **修复**: 释放内存但不保留图标，这样滚动回来时会重新加载
            item.thumbnail = QImage();
            item.isLoaded = false;
            releasedCount++;
            // 重置QListWidgetItem为占位符，确保滚动回来时能重新加载
            if (i < count()) {
                QListWidgetItem* listItem = this->item(i);
                if (listItem) {
                    QImage placeholder = NextGenPlaceholder::createLoading(QSize(m_itemWidth, m_itemHeight), "加载缩略图...");
                    QPixmap pixmap = QPixmap::fromImage(placeholder);
                    listItem->setIcon(QIcon(pixmap));
                }
            }
        }
    }
}
void VirtualThumbnailView::cleanupDistantItems()
{
    // 清理远离可见区域的项目
    manageThumbnailMemory();
}
void VirtualThumbnailView::preloadNearbyItems()
{
    // 预加载附近项目
    loadVisibleThumbnails();
}
int VirtualThumbnailView::getItemIndexAtPosition(int y) const
{
    return y / (m_itemHeight + m_spacing);
}
QRect VirtualThumbnailView::getItemRect(int index) const
{
    if (index < 0 || index >= m_allItems.size()) {
        return QRect();
    }
    return m_allItems[index].position;
}
bool VirtualThumbnailView::isItemVisible(int index) const
{
    if (index < 0 || index >= m_allItems.size()) {
        return false;
    }
    const ThumbnailItem& item = m_allItems[index];
    int startY = m_scrollPosition;
    int endY = startY + m_viewportHeight;
    bool visible = item.position.bottom() >= startY && item.position.top() <= endY;
    return visible;
}
void VirtualThumbnailView::updateScrollBar()
{
    if (m_allItems.isEmpty()) {
        return;
    }
    // 计算总高度
    int totalHeight = m_allItems.size() * (m_itemHeight + m_spacing);
    // 设置滚动条范围
    verticalScrollBar()->setRange(0, qMax(0, totalHeight - m_viewportHeight));
    verticalScrollBar()->setPageStep(m_viewportHeight);
    verticalScrollBar()->setSingleStep(m_itemHeight + m_spacing);
}
QString VirtualThumbnailView::getThumbnailCachePath(int index) const
{
    if (m_currentFileIdentity.isEmpty() || !m_cacheManager) {
        return QString();
    }
    QString cacheKey = FileIdentityManager::getCacheKey(m_currentFileIdentity);
    QString cacheDir = m_cacheManager->getCacheDirectory() + "/" + cacheKey + "/thumbnails";
    QString fileName = QString("thumb_%1.png").arg(index, 5, 10, QChar('0'));
    QString fullPath = cacheDir + "/" + fileName;
    return fullPath;
}
bool VirtualThumbnailView::isThumbnailCached(int index) const
{
    QString cachePath = getThumbnailCachePath(index);
    bool exists = QFile::exists(cachePath);
    return exists;
}
// 新增方法实现
void VirtualThumbnailView::refreshThumbnailsFromCache(const QString& fileIdentity)
{
    if (fileIdentity.isEmpty() || fileIdentity != m_currentFileIdentity) {
        return;
    }
    // 保存当前滚动位置，避免刷新时丢失
    int savedScrollValue = verticalScrollBar()->value();
    // **重要修复**：只加载可视区域和缓冲区的缩略图，避免一次性全量加载
    int startY = verticalScrollBar()->value();
    int endY = startY + height();
    // 使用系统方法获取可见项目范围，更准确
    QListWidgetItem* startItem = itemAt(QPoint(0, startY));
    QListWidgetItem* endItem = itemAt(QPoint(0, endY));
    int startIndex = startItem ? row(startItem) : 0;
    int endIndex = endItem ? row(endItem) : m_allItems.size() - 1;
    // 添加缓冲区
    startIndex = qMax(0, startIndex - m_bufferSize);
    endIndex = qMin(m_allItems.size() - 1, endIndex + m_bufferSize);
    int loadedCount = 0;
    // 只检查可视区域和缓冲区的项目
    for (int i = startIndex; i <= endIndex; ++i) {
        if (i < 0 || i >= m_allItems.size()) continue;
        ThumbnailItem& item = m_allItems[i];
        // TDD: 如果项目未加载，使用统一缓存加载
        if (!item.isLoaded) {
            QImage unifiedThumbnail = loadThumbnailFromUnifiedCache(i);
            if (!unifiedThumbnail.isNull()) {
                item.thumbnail = unifiedThumbnail.scaled(m_itemWidth, m_itemHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation);
                item.isLoaded = true;
                loadedCount++;
                // 发送渐进式加载完成信号（但不在处理中时触发主图更新）
                emit thumbnailProgressivelyLoaded(i);
            }
        }
    }
    // 检查刷新后滚动位置是否发生变化
    int currentScrollValue = verticalScrollBar()->value();
    // 恢复滚动位置，避免刷新时滚动位置被重置
    if (savedScrollValue != currentScrollValue) {
        verticalScrollBar()->setValue(savedScrollValue);
    }
}
void VirtualThumbnailView::enableProgressiveLoading(bool enabled)
{
    m_progressiveLoadingEnabled = enabled;
    if (enabled && !m_currentFileIdentity.isEmpty()) {
        // 启动渐进式更新定时器
        if (m_progressiveTimer && !m_progressiveTimer->isActive()) {
            m_progressiveTimer->start();
        }
    } else {
        // 停止渐进式更新定时器
        if (m_progressiveTimer && m_progressiveTimer->isActive()) {
            m_progressiveTimer->stop();
        }
    }
}
void VirtualThumbnailView::setProgressiveUpdateInterval(int intervalMs)
{
    m_progressiveUpdateInterval = qMax(500, intervalMs); // 最小500ms
    if (m_progressiveTimer) {
        m_progressiveTimer->setInterval(m_progressiveUpdateInterval);
    }
}
void VirtualThumbnailView::performProgressiveUpdate()
{
    if (m_currentFileIdentity.isEmpty()) {
        return;
    }
    // 避免过于频繁的更新
    QDateTime now = QDateTime::currentDateTime();
    if (m_lastProgressiveUpdate.isValid() && 
        m_lastProgressiveUpdate.msecsTo(now) < m_progressiveUpdateInterval / 2) {
        return;
    }
    m_lastProgressiveUpdate = now;
    // **关键修复**: 首先检查是否需要扩展页面范围
    checkNeedMoreThumbnails();
    // **新增**: 检查可见区域是否有新生成的缓存文件
    if (!m_allItems.isEmpty()) {
        int startY = verticalScrollBar()->value();
        int endY = startY + height();
        // 使用系统方法获取可见项目范围
        QListWidgetItem* startItem = itemAt(QPoint(0, startY));
        QListWidgetItem* endItem = itemAt(QPoint(0, endY));
        int startIndex = startItem ? row(startItem) : 0;
        int endIndex = endItem ? row(endItem) : m_allItems.size() - 1;
        // **增强预加载范围**: 提升缩略图预加载能力
        int preloadRange = 8;
        startIndex = qMax(0, startIndex - preloadRange);
        endIndex = qMin(m_allItems.size() - 1, endIndex + preloadRange);
        // 检查可见区域的新缓存文件
        for (int i = startIndex; i <= endIndex; ++i) {
            if (i < 0 || i >= m_allItems.size()) continue;
            ThumbnailItem& item = m_allItems[i];
            if (!item.isLoaded && !item.isLoading) {
                // 检查是否有新生成的缓存文件
                if (checkAndLoadNewThumbnail(i)) {
                }
            }
        }
    }
}
bool VirtualThumbnailView::checkAndLoadNewThumbnail(int index)
{
    // **线程安全检查**: 防止并发访问
    QMutexLocker locker(&m_checkMutex);
    if (index < 0 || index >= m_allItems.size()) {
        return false;
    }
    ThumbnailItem& item = m_allItems[index];
    // 如果已经加载或正在加载，跳过
    if (item.isLoaded || item.isLoading) {
        return false;
    }
    // 检查缩略图文件是否存在且比上次检查时更新
    if (isThumbnailCached(index) && isThumbnailFileNewer(index)) {
        // TDD: 使用统一缓存加载新缩略图
        QImage unifiedThumbnail = loadThumbnailFromUnifiedCache(index);
        if (!unifiedThumbnail.isNull()) {
            ThumbnailItem& item = m_allItems[index];
            item.thumbnail = unifiedThumbnail.scaled(m_itemWidth, m_itemHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation);
            item.isLoaded = true;
            item.isLoading = false;
            // 发送渐进式加载完成信号
            emit thumbnailProgressivelyLoaded(index);
        }
        return true;
    }
    return false;
}
void VirtualThumbnailView::checkForNewThumbnails()
{
    performProgressiveUpdate();
}
bool VirtualThumbnailView::isThumbnailFileNewer(int index) const
{
    QString cachePath = getThumbnailCachePath(index);
    if (!QFile::exists(cachePath)) {
        return false;
    }
    QFileInfo fileInfo(cachePath);
    QDateTime fileTime = fileInfo.lastModified();
    // 如果文件是在最近几秒内创建/修改的，认为是新的
    QDateTime now = QDateTime::currentDateTime();
    return fileTime.secsTo(now) < 10; // 10秒内的文件认为是新的
}
void VirtualThumbnailView::expandTotalPages(int newTotalPages)
{
    if (newTotalPages <= m_allItems.size()) {
        return; // 不需要扩展
    }
    // 扩展项目列表
    for (int i = m_allItems.size(); i < newTotalPages; ++i) {
        ThumbnailItem item;
        item.index = i;
        item.isLoaded = false;
        item.isLoading = false;
        item.position = QRect(0, i * (m_itemHeight + m_spacing), m_itemWidth, m_itemHeight);
        item.cachePath = getThumbnailCachePath(i);
        m_allItems.append(item);
        // 创建QListWidgetItem
        QListWidgetItem* listItem = new QListWidgetItem(this);
        listItem->setSizeHint(QSize(m_itemWidth, m_itemHeight + 24)); // 为页码文字预留更多空间
        listItem->setText(QString("  %1  ").arg(i + 1)); // 显示页码，前后加空格控制位置
        listItem->setTextAlignment(Qt::AlignHCenter | Qt::AlignBottom); // 水平居中，垂直底部对齐
        // 设置占位符图标
        QImage placeholder = NextGenPlaceholder::createLoading(QSize(m_itemWidth, m_itemHeight), "加载缩略图...");
        QPixmap pixmap = QPixmap::fromImage(placeholder);
        listItem->setIcon(QIcon(pixmap));
    }
    m_totalPages = newTotalPages;
    // 更新滚动条以支持新的页面范围
    updateScrollBar();
}
// 动态边界扩展方法实现
void VirtualThumbnailView::checkNeedMoreThumbnails()
{
    if (m_currentFileIdentity.isEmpty()) {
        return;
    }
    // **关键修复**: 首先检查是否需要扩展页面范围
    // 检查缓存中是否有更多页面
    QString cacheKey = FileIdentityManager::getCacheKey(m_currentFileIdentity);
    QString cacheDir = m_cacheManager->getCacheDirectory() + "/" + cacheKey;
    QDir dir(cacheDir);
    if (dir.exists()) {
        QStringList pageFiles = dir.entryList(QStringList() << "page_*.png", QDir::Files);
        int actualPages = pageFiles.size();
        // **关键修复**: 如果实际页面数大于当前项目数，需要扩展
        if (actualPages > m_allItems.size() && actualPages > 1) {
            expandTotalPages(actualPages);
        }
    }
    // 然后检查可见区域的缩略图加载
    if (m_allItems.isEmpty()) {
        return;
    }
    // 计算当前可见区域
    int startY = verticalScrollBar()->value();
    int endY = startY + height();
    // 使用系统方法获取可见项目范围
    QListWidgetItem* startItem = itemAt(QPoint(0, startY));
    QListWidgetItem* endItem = itemAt(QPoint(0, endY));
    int startIndex = startItem ? row(startItem) : 0;
    int endIndex = endItem ? row(endItem) : m_allItems.size() - 1;
    // **增强预加载范围**: 提升缩略图预加载能力
    int preloadRange = 8;
    startIndex = qMax(0, startIndex - preloadRange);
    endIndex = qMin(m_allItems.size() - 1, endIndex + preloadRange);
    // 检查是否有未加载到内存的缩略图
    QList<int> needLoadIndices;
    for (int i = startIndex; i <= endIndex; ++i) {
        const ThumbnailItem& item = m_allItems[i];
        if (!item.isLoaded && !item.isLoading) {
            needLoadIndices.append(i);
        }
    }
    if (!needLoadIndices.isEmpty()) {
        // TDD: 使用统一缓存加载这些缩略图到内存
        for (int index : needLoadIndices) {
            if (index >= 0 && index < m_allItems.size()) {
                QImage unifiedThumbnail = loadThumbnailFromUnifiedCache(index);
                if (!unifiedThumbnail.isNull()) {
                    ThumbnailItem& item = m_allItems[index];
                    item.thumbnail = unifiedThumbnail.scaled(m_itemWidth, m_itemHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation);
                    item.isLoaded = true;
                    item.isLoading = false;
                }
            }
        }
    }
}
void VirtualThumbnailView::requestMoreThumbnailsIfNeeded()
{
    // 检查是否滚动到边界附近
    if (isScrollingNearBoundary()) {
        checkNeedMoreThumbnails();
    }
}
bool VirtualThumbnailView::isScrollingNearBoundary() const
{
    if (m_allItems.isEmpty()) {
        return false;
    }
    int scrollValue = verticalScrollBar()->value();
    int maxScroll = verticalScrollBar()->maximum();
    int viewportHeight = height();
    // **修复**: 更激进的边界检测
    // 如果滚动到底部附近（剩余不到1个视口高度）
    bool nearBottom = (maxScroll - scrollValue) < viewportHeight;
    // 如果滚动到顶部附近（不到1个视口高度）
    bool nearTop = scrollValue < viewportHeight;
    // **新增**: 检查是否滚动到了当前已加载内容的边界
    QListWidgetItem* currentItem = itemAt(QPoint(0, scrollValue + viewportHeight / 2));
    int currentIndex = currentItem ? row(currentItem) : -1;
    bool nearLoadedBoundary = false;
    // 检查是否接近已加载内容的边界
    if (currentIndex >= 0 && currentIndex < m_allItems.size()) {
        // 向前检查5个项目，看是否有未加载的
        for (int i = currentIndex; i < qMin(currentIndex + 5, m_allItems.size()); ++i) {
            if (!m_allItems[i].isLoaded) {
                nearLoadedBoundary = true;
                break;
            }
        }
        // 向后检查5个项目，看是否有未加载的
        for (int i = qMax(0, currentIndex - 5); i < currentIndex; ++i) {
            if (!m_allItems[i].isLoaded) {
                nearLoadedBoundary = true;
                break;
            }
        }
    }
    bool result = nearBottom || nearTop || nearLoadedBoundary;
    return result;
}
// TDD: 统一缓存加载方法实现
QImage VirtualThumbnailView::loadThumbnailFromUnifiedCache(int index)
{
    if (!m_unifiedMemoryManager) {
        return QImage();
    }
    // TDD: 确保统一内存管理器使用正确的文件标识
    // 为统一内存管理器设置当前文件标识
    if (m_unifiedMemoryManager) {
        // 使用安全的类型转换，避免崩溃
        try {
            auto* manager = dynamic_cast<MinimalUnifiedMemoryManager*>(m_unifiedMemoryManager);
            if (manager) {
                manager->setCurrentFileIdentity(m_currentFileIdentity);
            }
        } catch (...) {
        }
    }
    // 使用统一内存管理器加载缩略图
    QImage image = m_unifiedMemoryManager->getImage(
        IUnifiedMemoryManager::ContentType::THUMBNAIL, 
        index,
        (count() > 0) ? (verticalScrollBar()->value() / (m_itemHeight + m_spacing)) : -1
    );
    return image;
}
// TDD: 设置统一内存管理器
void VirtualThumbnailView::setUnifiedMemoryManager(IUnifiedMemoryManager* manager)
{
    m_unifiedMemoryManager = manager;
}
